from flask import Flask
from settings import map_config


# 负责创建app
def create_app(config_type):
    app = Flask(__name__)
    # 加载项目配置
    app.config.from_object(map_config.get(config_type))

    # 初始化限流器
    from common.utils.limiter import limiter as lmt
    lmt.init_app(app) # 关联app

    # 加载日志处理的工具
    from common.utils.logging import create_logger
    create_logger(app)

    # 初始化Redis数据库连接
    from common.utils.shopping_redis import redis_client
    redis_client.init_app(app)

    # 初始化 SQLALchemy
    from common.models import db
    db.init_app(app)

    # 添加全局请求钩子
    from common.utils.request_wares import jwt_request_authorization
    app.before_request(jwt_request_authorization) # 所有服务器的请求都有当前的请求钩子


    # 加载模块的蓝图
    from shopping.resource.user import user_bp
    from shopping.resource.index import index_bp
    from shopping.resource.goods import goods_bp
    from shopping.resource.coupon import coupon_bp
    from shopping.resource.cart import cart_bp
    from shopping.resource.address import address_bp
    from shopping.resource.order import order_bp

    # 注册蓝图
    app.register_blueprint(user_bp,url_prefix='/user')
    app.register_blueprint(index_bp,url_prefix='/index')
    app.register_blueprint(goods_bp,url_prefix='/goods')
    app.register_blueprint(coupon_bp,url_prefix='/coupon')
    app.register_blueprint(cart_bp, url_prefix='/cart')
    app.register_blueprint(address_bp, url_prefix='/address')
    app.register_blueprint(order_bp, url_prefix='/order')

    return app